package com.example.student_blocket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class RegisterActivity extends Activity {

	private final String REGISTER = Singleton.getInstance().getHOST() + "shop-app/create-user.php";
	private final String CHECK_USERNAME = Singleton.getInstance().getHOST() + "shop-app/select-username.php";
	private final boolean DEBUG = Singleton.getInstance().isDebug();
	private Button registerButton;
	private EditText username;
	private EditText password;
	private EditText rePassword;
	private EditText firstLastNames;
	private EditText email;
	private EditText address;
	private EditText phoneNumber;
	private Misc misc = new Misc();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		setContentView(R.layout.activity_register);
		
		iniUserInputContainers();
		iniRegistrationButton();
	}
	
	private void iniRegistrationButton() {
		registerButton = (Button) findViewById(R.id.rp_btn_reg);
		registerButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!DEBUG) {
					if (misc.validateUsername(username) 
							&& misc.validatePassword(password)
							&& misc.checkPasswords(password, rePassword)
							&& misc.validateFirstLastName(firstLastNames.getText().toString())
							&& misc.validateEmail(email.getText().toString())) {
						new RegisterTask().execute();
					} else {
						if (!misc.validateUsername(username)) {
							misc.showErrorMessage("Username field is empty!",getApplicationContext());
						} else if(!misc.validatePassword(password)) {
							misc.showErrorMessage("Password field is empty or less than 6 characters!",getApplicationContext());
						} else if(!misc.validatePassword(rePassword)) {
							misc.showErrorMessage("Re-type password field is empty!",getApplicationContext());
						} else if (!misc.checkPasswords(password, rePassword)) {
							misc.showErrorMessage("The retyped password doesn't match the original!",getApplicationContext());
						} else if(!misc.validateFirstLastName(firstLastNames.getText().toString())) {
							misc.showErrorMessage("First Last Name field is empty!",getApplicationContext());
						} else if(!misc.validateEmail(email.getText().toString())) {
							misc.showErrorMessage("The email field is empty or the email is incorrect!",getApplicationContext());
						} else {
							misc.showErrorMessage("Opppass!",getApplicationContext());
						}
					}
				} else {
					startActivity(new Intent(RegisterActivity.this,MainActivity.class));
				}
			}
		});
		
	}
	@Override
	public void onBackPressed() {
		startActivity(new Intent(RegisterActivity.this, MainActivity.class));
		finish();
	}
	private void iniUserInputContainers() {
		username = (EditText) findViewById(R.id.usernameInputReg);
		password = (EditText) findViewById(R.id.passwordInputReg);
		rePassword = (EditText) findViewById(R.id.rePasswordInputReg);
		firstLastNames = (EditText) findViewById(R.id.namesInputReg);
		email = (EditText) findViewById(R.id.emailInputReg);
		address = (EditText) findViewById(R.id.addressInputReg);
		phoneNumber = (EditText) findViewById(R.id.phoneInputReg);
	}
	
	
	
	private class RegisterTask extends AsyncTask<String, String, Boolean> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        
	        pDialog = new ProgressDialog(RegisterActivity.this);
	        pDialog.setMessage("Registering...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(true);
	        pDialog.show();
	    }
		
		@Override
		protected Boolean doInBackground(String... params) {
			boolean usernameAvailable = false;
			boolean registered = false;
			JSONParser jParser = new JSONParser();
			String usernameIn = username.getText().toString();
            
            List<NameValuePair> paras = new ArrayList<NameValuePair>();
            paras.add(new BasicNameValuePair("username", usernameIn));
 
			JSONObject json = jParser.makeHttpRequest(CHECK_USERNAME,paras);
	        try {
				int result = json.getInt("affected");
				if (result == 1) {
					usernameAvailable = false;
				} else {
					usernameAvailable = true;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
	        
	        if (usernameAvailable) {
	        	String passwordIn = password.getText().toString();
		        String[] namesIn = firstLastNames.getText().toString().split(" ");
		        String firstName = namesIn[0];
		        String lastName = namesIn[1];
		        String addressIn = "";
		        if (misc.validateAddress(address)) {
					addressIn = address.getText().toString();
				} else {
					addressIn = null;
				}
		        
		        String phoneIn = "";
	            if (misc.validatePhoneNumber(phoneNumber)) {
					phoneIn = phoneNumber.getText().toString();
				} else {
					phoneIn = null;
				}
	            
	            String emailIn = email.getText().toString();
	            List<NameValuePair> paras1 = new ArrayList<NameValuePair>();
	            paras1.add(new BasicNameValuePair("c_username", usernameIn));
	            paras1.add(new BasicNameValuePair("c_password", passwordIn));
	            paras1.add(new BasicNameValuePair("first_name", firstName));
	            paras1.add(new BasicNameValuePair("last_name", lastName));
	            paras1.add(new BasicNameValuePair("address", addressIn));
	            paras1.add(new BasicNameValuePair("telephone", phoneIn));
	            paras1.add(new BasicNameValuePair("email", emailIn));
	            
				JSONObject json1 = jParser.makeHttpRequest(REGISTER,paras1);
		        try {
					int result = json1.getInt("affected");
					if (result == 1) {
						registered = true;
					} else {
						registered = false;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				registered = false;
			}
	        return registered;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				Intent intent = new Intent(getApplicationContext(), MainActivity.class);
				startActivity(intent);
				finish();
			} else {
				misc.showErrorMessage("The username is not available.", getApplicationContext());
			}
			pDialog.dismiss();
        }
	}
}
